import 'package:dio/dio.dart';
import 'package:znmm/UI/utils/my_global.dart';
import 'package:znmm/network/dio_https.dart';
import 'package:znmm/network/notify_listener.dart';
import 'package:znmm/network/web_socket_channel.dart';
import 'package:mime/mime.dart';
import 'package:http_parser/http_parser.dart';

class EdtiTempMag {
  static final EdtiTempMag _instance = EdtiTempMag._internal();

  factory EdtiTempMag() {
    return _instance;
  }

  EdtiTempMag._internal();

  void doSomething() {
    print("Doing something...");
  }

  void clean() {
    _webSocketChannel.close();
  }

  ///websocket
  final MyWebSocketChannel _webSocketChannel = MyWebSocketChannel();
  MyWebSocketChannel get webSocketChannel => _webSocketChannel;

  ///链接socket
  void _connectToWebSocket(Map<String, dynamic> param,
      {void Function(String)? callback}) {
    String autoTextStr = '';
    _webSocketChannel.close();
    String token = ""; //UserInfoManage().getUserInfo().token;
    String username = ""; //UserInfoManage().getUserInfo().username;

    String strToken = ""; //UserInfoManage().getUserInfo().token;

    if (strToken.isEmpty) {
      MyGlobal.showInfo("缺少token,请先登录!");
      return;
    }

    String url = '${PTWSUrl.gptWebSocketUrl}?username=$username&token=$token';

    print("WebSocket URL: $url");
    _webSocketChannel.connect(
      url: url,
      onConnectSuccess: () {
        print('WebSocket connected successfully!');

        _webSocketChannel.sendMessage(
          jsonEncode(param),
          //json.encode(param), //jsonEncode(param)
          onSendMessageSuccess: () {
            print("onSendMessageSuccess");
            MyGlobal.hideLoading();
          },
          onSendMessageFailure: (p0) {
            print("onSendMessageFailure");
            MyGlobal.hideLoading();
          },
        );
      },
      onDataReceived: (data) {
        print('Received data: $data');
        MyGlobal.hideLoading();

        try {
          Map result = jsonDecode(data);

          if (result['end'] == false) {
            ///生成的文本拼接
            autoTextStr = autoTextStr + result['message'];
          } else {
            autoTextStr = autoTextStr + result['message'];
            print('gptmessage: $autoTextStr');

            if (callback != null) {
              callback(autoTextStr);
            }
          }

          insertText(autoTextStr);
        } catch (e) {
          //print('Error parsing data: $e');
          //Toast.showMsg("$e");
        }
      },
      onConnectFailure: (error) {
        //print('WebSocket connection failed: $error');
        MyGlobal.showInfo("链接失败:$error");
        MyGlobal.hideLoading();
      },
    );
  }

  ///--------------------------------自动生成
  void autoTemplateData(String autoConStr, {void Function(String)? callback}) {
    if (autoConStr.isEmpty) {
      MyGlobal.showInfo('请输入内容');
      return;
    }
    Map<String, dynamic> param = {
      "type": "message",
      "message": autoConStr,
      "uuid": '110',
    };
    MyGlobal.showLoading();
    _connectToWebSocket(param, callback: callback);
  }

  ///引用gpt生成的文本开发信
  ///
  void insertText(String autoTextStr) {
    var jsondata = jsonEncode(autoTextStr);
    var data = jsondata.replaceAll('\\n', '<br>');
    //判断首字符和尾字符是否为引号，是则去掉
    if (data.startsWith('"') && data.endsWith('"')) {
      data = data.substring(1, data.length - 1);
    }
    //去除转义字符
    data = data.replaceAll('\\', '');
    print('autoText-------------: $data');
    //initHtml = data; //lufei_bug_2024_01_30

    NotifyCenter().postNotification(NotifyKey.templateEditKey, data: data);
  }

  //上传图片
  Future<String> onImagePickCallback(File file) async {
    String result = file.path;

    try {
      // 获取文件的MIME类型
      String mimeType = lookupMimeType(file.path) ?? 'application/octet-stream';

      // 创建 MultipartFile
      MultipartFile multipartFile = await MultipartFile.fromFile(
        file.path,
        contentType: MediaType.parse(mimeType),
      );

      // 将文件封装到 FormData 中
      FormData data = FormData.fromMap({
        "file": multipartFile,
      });
      // 需要token
      String strToken = ""; //UserInfoManage().getUserInfo().token;
      String strUsername = ""; //UserInfoManage().getUserInfo().username;
      // 使用 Dio 发送请求
      Dio dio = Dio();

      Response response = await dio.post(
        "https://enterprise-mailservice.pintreel.com/mail_api/mail/upload", // 替换为实际上传的URL
        data: data,
        options: Options(
          headers: {"token": strToken, "username": strUsername},
        ),
        onSendProgress: (int sent, int total) {
          print('Progress: ${(sent / total * 100).toStringAsFixed(0)}%');
        },
      );

      print("response: ${response.data}");
      if (response.data != null &&
          response.data is List &&
          response.data.isNotEmpty) {
        result = response.data[0];
      }
    } catch (e) {
      print("Error uploading file: $e");
    }

    // result =
    //     "https://enterprise-mailservice.pintreel.com/emailFile/157710301@qq.com/2024-09-21/3f535fed8c91ff0b0a76495c1246d81c/image_picker_B212E051-4CA6-4564-A03D-57111238DD11-66008-000014FA2FDC59A4.jpg";

    return result;
  }

  //创建模板
  void createTemplate(String nameText, String subTitleText, var html,
      {void Function()? callback}) async {
    Map data = {
      "name": nameText,
      "content": html,
      "subject": subTitleText,
      'attachments': [],
    };

    DioHttps dioUtil = DioHttps.instance!;
    //dioUtil.openLog();
    dioUtil
        .request<dynamic>(
      "https://credits.pintreel.com/api/mail-content/store",
      method: DioMethod.post,
      data: data,
      bIsShowResponse: true,
    )
        .then((response) {
      // 处理响应数据

      print("response:$response");
      if (response == null) {
        return;
      }
      MyGlobal.showInfo('创建成功');

      if (callback != null) {
        callback();
      }
    });
  }

  //语言
  ///语言列表
  List languageList = [
    {
      'id': 'en',
      'en': 'English',
      'zh': '英语',
    },
    {
      'id': 'fr',
      'en': 'French',
      'zh': '法语',
    },
    {
      'id': 'de',
      'en': 'German',
      'zh': '德语',
    },
    {
      'id': 'it',
      'en': 'Italian',
      'zh': '意大利语',
    },
    {
      'id': 'es',
      'en': 'Spanish',
      'zh': '西班牙语',
    },
    {
      'id': 'pt',
      'en': 'Portuguese',
      'zh': '葡萄牙语',
    },
    {
      'id': 'ru',
      'en': 'Russian',
      'zh': '俄语',
    },
    {
      'id': 'ja',
      'en': 'Japanese',
      'zh': '日语',
    },
    {
      'id': 'ko',
      'en': 'Korean',
      'zh': '韩语',
    },
    {
      'id': 'ar',
      'en': 'Arabic',
      'zh': '阿拉伯语',
    },
    {
      'id': 'zh',
      'en': 'Chinese',
      'zh': '中文',
    },
  ];

  ///语言风格列表
  List languageStyleList = [
    {
      'id': 'professional',
      'en': 'Profession',
      'zh': '专业',
    },
    {
      'id': 'speech',
      'en': 'Speech',
      'zh': '口语',
    },
    {
      'id': 'humorours',
      'en': 'Humorours',
      'zh': '幽默',
    },
    {
      'id': 'warm',
      'en': 'Warm',
      'zh': '热情',
    }
  ];

  ///邮件长度
  List emailList = [
    {
      'id': 'short',
      'en': 'Short',
      'zh': '短',
    },
    {
      'id': 'medium',
      'en': 'Medium',
      'zh': '中',
    },
    {
      'id': 'long',
      'en': 'Long',
      'zh': '长',
    }
  ];

  ///使用场景
  List useSceneList = [
    {
      'id': 'promotional',
      'en': 'Promotional Letter',
      'zh': '开发信',
    },
    {
      'id': 'product',
      'en': 'Product Introduction',
      'zh': '产品介绍',
    },
    {
      'id': 'holiday',
      'en': 'Holiday wishes',
      'zh': '节日祝福',
    },
  ];

  ///--------------------------------智能生成
  void aiAutoTemplate(
      String companyName,
      String productInfo,
      String companyAdvantage,
      String productAdvantage,
      String serviceAdvantage,
      String callToAction,
      String outputlanguage,
      String selectLanguageStyle,
      String selectEmailLength,
      String selectUseScene,
      {void Function(String)? callback}) {
    Map<String, dynamic> param = {
      "type": "message",
      "message": 'holle ',
      "uuid": "110",
      "extra_option": {
        "company_name": companyName,
        "product_info": productInfo,
        "output_language": languageList
            .firstWhere((element) => element['id'] == outputlanguage)['en'],
        "speech_style": languageStyleList.firstWhere(
            (element) => element['id'] == selectLanguageStyle)['en'],
        "length": emailList
            .firstWhere((element) => element['id'] == selectEmailLength)['en'],
        "usage_scenario": useSceneList
            .firstWhere((element) => element['id'] == selectUseScene)['en'],
        "company_advantage": companyAdvantage,
        "product_advantage": productAdvantage,
        "service_advantage": serviceAdvantage,
        "call_to_action": callToAction,
      }
    };

    MyGlobal.showLoading();
    _connectToWebSocket(param, callback: callback);
  }
}
